---
interface GlossaryEntry {
	compiledContent: () => Promise<string>;
	Content: any;
	file: string;
	toString: () => string;
}

const { id, label } = Astro.props;

if (!id) throw new Error("Modal id parameter is required");

const posts = import.meta.glob<GlossaryEntry>(
	"/src/content/docs/glossary/*.md",
	{
		eager: true,
	}
);

const regex = new RegExp(`${id}\\.md$|${id}\\.mdx$`);
const [path, post] =
	Object.entries(posts).find(([path]) => regex.test(path)) ?? [];
if (!post) throw new Error(`Glossary entry "${id}" not found`);

// Extract content safely with type checking
let htmlContent = "";
try {
	const content = await post.compiledContent();
	htmlContent = String(content);
} catch (e) {
	throw new Error(`Failed to extract content for "${id}": ${e.message}`);
}

if (!htmlContent) throw new Error(`Empty content for "${id}"`);

const htmlSplit = htmlContent.split("<hr>");
if (!htmlSplit.length) throw new Error(`Invalid content format for "${id}"`);

const basePath = `/${Astro.url.pathname.split("/")[1]}/`;
const glossaryUrl = `${basePath}glossary/${id}`;
const uniqueId = `modal-${id}-${crypto.randomUUID().slice(0, 6)}`;
---

<my-modal
	class="modal-dialog-button"
	tabindex="0"
	data-tippy-maxWidth="100"
	data-unique-id={uniqueId}
	data-html={`<div id="${uniqueId}-primary">${htmlSplit[0]}<hr color="#923458" class="glossary-separator"><div class="glossary-url-div" id="${uniqueId}-glossary-url">🟩 <a class="glossary-url" href=${glossaryUrl} target="_blank">Click here for the full Glossary entry</a></div></div>`}
	data-html-more={htmlSplit[1]}
>
	<a class="glossary-url dialog-button-open" id={`${uniqueId}-open`}>{label}</a>
</my-modal>

<script>
	class MyModal extends HTMLElement {
		constructor() {
			super();
			const uniqueId = this.dataset.uniqueId ?? "";
			const idPrimary = `${uniqueId}-primary`;
			const idDialog = `${uniqueId}-dialog`;
			const idContent = `${uniqueId}-content`;
			const buttonId = `${uniqueId}-open`;
			const buttonClose = `${uniqueId}-close`;
			const buttonMore = `${uniqueId}-more`;
			const showMore = `${uniqueId}-show-more`;
			const glossaryUrl = `${uniqueId}-glossary-url`;
			const html = this.dataset.html ?? "";
			const htmlMore = this.dataset.htmlMore ?? "";

			const body = document.querySelector("body");
			if (!body) {
				return;
			}

			body.insertAdjacentHTML(
				"beforeend",
				`<dialog class="modal-dialog" id="${idDialog}">
                    <div class="dialog-content" id="${idContent}"></div>
                    <div class="dialog-button">
                        <div class="dialog-show-more" id="${showMore}" style="display: none"></div>
                        <button class="dialog-button-close" id="${buttonClose}" type="reset">Close this Dialog</button>
                        <button class="dialog-button-more" id="${buttonMore}" type="reset">Show more</button>
                    </div>
                </dialog>`
			);

			const dialogDiv = document.getElementById(idContent);
			const dialogMoreDiv = document.getElementById(showMore);

			if (dialogDiv) {
				dialogDiv.innerHTML = html;
			}

			if (dialogMoreDiv) {
				dialogMoreDiv.innerHTML = htmlMore;
			}

			const primary = document.getElementById(idPrimary);
			const dialog = document.getElementById(idDialog);
			const openDialog = document.getElementById(buttonId);
			const closeDialog = document.getElementById(buttonClose);

			const toggleMore = document.getElementById(buttonMore);
			const moreDialog = document.getElementById(showMore);
			const dialogUrl = document.getElementById(glossaryUrl);

			if (!openDialog || !closeDialog || !dialog) {
				return;
			}

			// Update button opens a modal dialog
			openDialog.addEventListener("click", () => {
				(dialog as HTMLDialogElement).showModal();
			});

			// Form cancel button closes the dialog box
			closeDialog.addEventListener("click", () => {
				(dialog as HTMLDialogElement).close();
			});

			const toggleDisplay = (element: HTMLElement | null) => {
				if (element) {
					element.style.display =
						element.style.display === "none" ? "block" : "none";
				}
			};

			toggleMore?.addEventListener("click", () => {
				toggleDisplay(primary);
				toggleDisplay(dialogUrl);
				toggleDisplay(moreDialog);
				toggleMore.innerHTML =
					toggleMore.innerHTML === "Show less" ? "Show more" : "Show less";
			});

			// Close the dialog when clicked outside
			window.addEventListener("click", (event) => {
				if (event.target === dialog) {
					(dialog as HTMLDialogElement).close();
					if (moreDialog) {
						moreDialog.style.display = "none";
					}
					if (dialogUrl) {
						dialogUrl.style.display = "block";
					}
				}
			});

			const resetContent = () => {
				if (dialogDiv) {
					dialogDiv.style.display = "block";
				}
				if (moreDialog) {
					moreDialog.style.display = "none";
				}
				if (dialogUrl) {
					dialogUrl.style.display = "block";
				}
				if (primary) {
					primary.style.display = "block";
				}
				if (toggleMore) {
					toggleMore.innerHTML = "Show more";
				}
			};

			const handleClose = () => {
				resetContent();
				(dialog as HTMLDialogElement).close();
			};

			// Update all close handlers
			closeDialog.addEventListener("click", handleClose);

			window.addEventListener("click", (event) => {
				if (event.target === dialog) {
					handleClose();
				}
			});

			document.addEventListener("keydown", (event) => {
				if (event.key === "Escape" && dialog.open) {
					handleClose();
				}
			});
		}
	}
	customElements.define("my-modal", MyModal);
</script>

<style is:global>
	.glossary-separator {
		color: rgb(146, 52, 88) !important;
		margin: -10px 0px 0px 0px;
	}

	.glossary-url {
		margin: 0px 0px 0px 0px;
		color: blue !important;
	}

	.glossary-url-div {
		margin: 10px 0px 0px 0px;
	}

	.glossary-url {
		color: var(--url-colour) !important;
	}

	.glossary-url:hover {
		color: var(--url-colour-hover) !important;
		cursor: pointer;
	}

	.modal-dialog {
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		max-width: 100%;
		min-width: 400px;
		height: max-content;
		border: 2px solid rgb(146, 52, 88);
		line-height: 20px;
		border-radius: 5px;
	}

	.dialog-button {
		float: none !important;
		padding-top: 10px !important;
		padding-bottom: 0px !important;
	}

	.dialog-button-close {
		width: 49% !important;
		float: left !important;
		border: 2px solid rgb(146, 52, 88);
		padding: 10px;
		border-radius: 5px;
	}

	.dialog-button-more {
		width: 49% !important;
		float: right !important;
		border: 2px solid rgb(146, 52, 88);
		padding: 10px;
		border-radius: 5px;
	}

	.dialog-content {
		padding: 0px !important;
		margin-bottom: 0px !important;
		white-space: pre-wrap !important;
	}

	.dialog-show-more {
		padding-bottom: 10px !important;
		margin-top: -30px !important;
		white-space: pre-wrap !important;
	}

	.dialog-button-open {
		border-radius: 2px !important;
		color: var(--modal-url-color) !important;
		padding: 0px 2px 2px 2px !important;
		background-color: var(--modal-url-bg-color) !important;
	}

	.dialog-button-open:hover {
		background-color: var(--modal-url-bg-hv-color) !important;
		color: var(--modal-url-hover-color) !important;
	}

	dialog.modal-dialog::backdrop {
		background-color: rgba(0, 0, 0, 0.5);
		backdrop-filter: blur(3px);
	}
</style>
